package com.mantru.iotpot.Cleaning;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.mantru.iotpot.ApplicationClass;
import com.mantru.iotpot.Cook.CookActivity;
import com.mantru.iotpot.Cook.PutFoodActivity;
import com.mantru.iotpot.R;
import com.mantru.iotpot.Tools.LoadingDialogUtil;
import com.mantru.iotpot.Tools.tools;
import com.mantru.iotpot.Util.ToastUtils;
import com.mantru.iotpot.eventbus.EventMessage;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class CleaningActivity extends AppCompatActivity implements View.OnClickListener {
    private ApplicationClass ac;
    private TextView time;
    private TextView name;
    private Handler handler;
    private Runnable updateRunnable;
    private int type;
    private Button stop;
    private AlertDialog dialog; // 用于存储弹窗对象
    private CountDownTimer timer;
    private Button back;
    private Button put_water;
    private LinearLayout linearLayout;
    private Dialog dialog1;
    private int ErrorGripper = 0;//0表示机械臂没有故障，1表示机械臂出现故障
    private String TAG = "CleaningActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cleaning);
        ac = (ApplicationClass) getApplication(); // 初始化 ApplicationClass
        EventBus.getDefault().register(this);
        Intent intent = getIntent();
        type = intent.getIntExtra("type", -1);
        boolean result = ac.Cleaning_Start(type);
        Log.d("cleaning", "result: " + result);
        name = findViewById(R.id.wash_name);
        time = findViewById(R.id.wash_time);
        stop = findViewById(R.id.wash_stop);
        back = findViewById(R.id.wash_back);
        put_water = findViewById(R.id.wash_put_water);
        linearLayout = findViewById(R.id.put_water_LinearLayout);
        stop.setOnClickListener(this);
        back.setOnClickListener(this);
        put_water.setOnClickListener(this);
        String statusText = "";
        if (type == 1) {
            statusText = "快速洗";
        } else if (type == 2) {
            statusText = "普通洗";
        } else if (type == 3) {
            statusText = "加强洗";
        } else if (type == 4) {
            statusText = "自定义清洗";
        }
        name.setText(statusText);
        stop.setOnClickListener(this);
        updateUI();//更新洗锅状态
        if (result) {
            // 创建Handler用于在主线程中更新UI
            handler = new Handler(Looper.getMainLooper());
            updateRunnable = new Runnable() {
                @Override
                public void run() {
                    updateUI();
                    handler.postDelayed(this, 1000); // 每秒刷新一次
                }
            };
            // 开始定时更新UI
            handler.post(updateRunnable);
        } else {
            Toast.makeText(this, "洗锅失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void updateUI() {
        // 更新洗锅状态
        // 更新剩余时间
        if (ac.jobmaster.steep_status == 2){//洗锅完成
            handler.removeCallbacks(updateRunnable);
            stop.setVisibility(View.GONE);
            linearLayout.setVisibility(View.VISIBLE);
            time.setVisibility(View.INVISIBLE);
            name.setText("洗锅完成");
        } else if (ac.jobmaster.steep_status == 0) {
            showDialog();
        }else {
            dismissDialog();
        }
        String timeText = "剩余时间: " + ac.jobmaster.remain_time + "s";
        Log.d("wash","time: " + timeText);
        time.setText(timeText);
    }

    @Override
    protected void onDestroy() {
        // 移除定时任务，避免内存泄漏
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
        // 关闭弹窗
        dismissDialog();
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.wash_stop) {//终止洗锅
            String title = "提示";
            String content = "确认要终止洗锅吗？";
            tools.showCustomDialog(this, title, content, new tools.OnDialogButtonClickListener() {
                @Override
                public void onConfirmClick() {
                    // 点击确认按钮后的逻辑
                    ToastUtils.show(CleaningActivity.this,"确认");
                    ac.Cleaning_Stop();
                    stop.setVisibility(View.GONE);
                    linearLayout.setVisibility(View.VISIBLE);
                    time.setVisibility(View.INVISIBLE);
                    name.setText("洗锅已终止");
                }
                @Override
                public void onCancelClick() {
                    // 点击取消按钮后的逻辑
                    ToastUtils.show(CleaningActivity.this,"取消");
                }
            });
        } else if (v.getId() == R.id.wash_back) {//返回首页
//            LoadingDialogUtil.showLoadingDialog(CleaningActivity.this);
            finish();
        } else if (v.getId() == R.id.wash_put_water) {//倒水
            boolean result = ac.Cleaning_PourOut();
            if (result){
                if (ErrorGripper == 0){
                    startActivity(new Intent(this, PutWaterActivity.class));
                    finish();
                } else if (ErrorGripper == 1) {
                    ShowCheakDialog();
                }
            }else{
                ToastUtils.show(this,"倒水失败");
            }
//            LoadingDialogUtil.showLoadingDialog(CleaningActivity.this);
//            startActivity(new Intent(this, PutWaterActivity.class));
//            finish();
        }
    }

    private void showDialog() {
        // 如果弹窗已经显示，则不重复显示
        if (dialog != null && dialog.isShowing()) {
            return;
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View dialogView = getLayoutInflater().inflate(R.layout.waitcook, null);
        builder.setView(dialogView);

        // 获取弹窗中的按钮和计时器文本
        final TextView countdownTextView = dialogView.findViewById(R.id.countdownTextView);
        timer = new CountDownTimer(60 * 1000,1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                countdownTextView.setText((millisUntilFinished / 1000) + "S");
            }
            @Override
            public void onFinish() {
                // 如果弹窗存在且正在显示，则关闭它
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
                if ( timer != null ){
                    timer.cancel();
                    timer = null;
                }
                finish();
                Toast.makeText(CleaningActivity.this,"设备就位失败，请重试！",Toast.LENGTH_SHORT).show();
            }
        };
        timer.start();
        // 创建并显示弹窗
        dialog = builder.create();
        dialog.show();
        // 关键代码：设置窗口背景透明
        if (dialog.getWindow() != null) {
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        }
        // 关键代码：设置点击外部不可取消
        dialog.setCanceledOnTouchOutside(false);
        // 保存计时器和弹窗引用，以便在状态改变时停止计时器和关闭弹窗
        this.dialog = dialog;
        this.handler = handler;
    }

    // 关闭弹窗
    private void dismissDialog() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
            if ( timer != null ){
                timer.cancel();
                timer = null;
            }
        }
    }

//    private BroadcastReceiver receiver = new BroadcastReceiver() {
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            if ("ACTION_CLOSE_LOADING_DIALOG".equals(intent.getAction())) {
//                LoadingDialogUtil.closeLoadingDialog();
//            }
//        }
//    };

    @Override
    protected void onStart() {
        super.onStart();
//        LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter("ACTION_CLOSE_LOADING_DIALOG"));
    }

    @Override
    protected void onStop() {
        super.onStop();
//        LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        // 在界面渲染完成后发送广播关闭弹窗
//        new Handler().post(new Runnable() {
//            @Override
//            public void run() {
//                ((ApplicationClass) getApplication()).sendBroadcast("ACTION_CLOSE_LOADING_DIALOG");
//            }
//        });
    }

    private void ShowCheakDialog(){
        // 如果弹窗已经显示，则不重复显示
        if (dialog1 != null && dialog1.isShowing()) {
            return;
        }
        // 创建自定义对话框
        dialog1 = new Dialog(this);
        dialog1.setContentView(R.layout.manual_cheak_dialog); // 设置对话框的布局

        Button stop = dialog1.findViewById(R.id.manual_cheak_dialog_stop);
        Button low = dialog1.findViewById(R.id.manual_cheak_dialog_low);
        Button rotate = dialog1.findViewById(R.id.manual_cheak_dialog_rotate);

        stop.setOnClickListener(v -> {
            ac.Device_SendCommand_Gripper_Stop();
            ac.SaveLog("用户点击了炒菜爪手动寻位的停止按钮");
        });

        low.setOnClickListener(v -> {
            ac.Device_SendCommand_Gripper_Slow();
            ac.SaveLog("用户点击了炒菜爪手动寻位的低速按钮");
        });

        rotate.setOnClickListener(v -> {
            ac.Device_SendCommand_Gripper_OK();
            ac.SaveLog("用户点击了炒菜爪手动寻位的确认按钮");
            dialog1.dismiss();
//            LoadingDialogUtil.showLoadingDialog(CleaningActivity.this);
            startActivity(new Intent(this, PutWaterActivity.class));
            finish();
        });
        // 关键代码：设置窗口背景透明
        if (dialog1.getWindow() != null) {
            dialog1.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        }

        dialog1.setCanceledOnTouchOutside(false);

        // 显示对话框
        dialog1.show();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBusMessage(EventMessage event){
        if (event.id == EventMessage.MSG_ID_ErrorGripper){//收到了机械臂出现故障的消息
            ErrorGripper = 1;
            ac.SaveLog(TAG + " 界面接收到机械臂出现故障的事件");
        }
    }
}